package com.ruoyi.workflow.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.PageDomain;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.page.TableSupport;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.workflow.domain.CarPackageAudit;
import com.ruoyi.workflow.service.ICarPackageAuditService;
import com.ruoyi.workflow.service.IDoneTaskService;
import com.ruoyi.workflow.vo.CarPackageAuditVo;
import com.ruoyi.workflow.vo.HistoryActivity;
import org.activiti.engine.HistoryService;
import org.activiti.engine.TaskService;
import org.activiti.engine.history.HistoricActivityInstance;
import org.activiti.engine.history.HistoricProcessInstance;
import org.activiti.engine.history.HistoricTaskInstance;
import org.activiti.engine.task.Comment;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DoneTaskServiceImpl implements IDoneTaskService {
    @Autowired
    private HistoryService historyService;
    @Autowired
    private ICarPackageAuditService carPackageAuditService;
    @Autowired
    private ISysUserService userService;
    @Autowired
    private TaskService taskService;
    @Override
    public TableDataInfo selectHistoryAuditList(CarPackageAudit carPackageAudit) {
        //创建返回对象
        TableDataInfo tableDataInfo = new TableDataInfo();
        tableDataInfo.setCode(200);
        tableDataInfo.setMsg("查询成功");
        //根据当前登录的用户获取代办任务数量进行分页
        String username = SecurityUtils.getUsername();

        long count = historyService.createHistoricTaskInstanceQuery().taskAssignee(username).count();
        tableDataInfo.setTotal(count);
        if (count == 0) {
            tableDataInfo.setRows(Collections.emptyList());
            return tableDataInfo;
        }
        //接收分页查询参数
        PageDomain pageDomain = TableSupport.buildPageRequest();
        Integer pageNum = pageDomain.getPageNum();
        Integer pageSize = pageDomain.getPageSize();
        Integer startIndex = (pageNum - 1) * pageSize;
        List<CarPackageAudit> auditList = new ArrayList<>();
        //查询当前用户的任务,一个任务对应一条数据
        List<HistoricTaskInstance> taskList = historyService.createHistoricTaskInstanceQuery().taskAssignee(username).finished().orderByTaskCreateTime().desc().listPage(startIndex, pageSize);
        for (HistoricTaskInstance t : taskList
        ) {
            //查询审核记录--对应一个流程实例
            //基于任务获取流程实例对象
            HistoricProcessInstance historicProcessInstance = historyService.createHistoricProcessInstanceQuery().processInstanceId(t.getProcessInstanceId()).singleResult();
            //基于流程实例对象获取业务标识
            String businessKey = historicProcessInstance.getBusinessKey();
            //基于businessKey获取审批记录
            CarPackageAudit audit = carPackageAuditService.getBaseMapper().selectById(businessKey);
            //设置创建人名称
            SysUser sysUser = userService.selectUserById(Long.valueOf(audit.getCreatorId()));
            audit.setCreatorName(sysUser.getUserName());
            //将CarPackageAudit拷贝到vo对象中
            CarPackageAuditVo carPackageAuditVo = new CarPackageAuditVo();
            BeanUtils.copyProperties(audit, carPackageAuditVo);
            //为当前审核记录设置任务ID,名称和候选人名称
            carPackageAuditVo.setTaskId(t.getId());
            carPackageAuditVo.setTaskName(t.getName());
            carPackageAuditVo.setAuditsName(SecurityUtils.getUsername());
            carPackageAuditVo.setEndTime(historicProcessInstance.getEndTime());
            auditList.add(carPackageAuditVo);
        }

        tableDataInfo.setRows(auditList);

        return tableDataInfo;
    }

    @Override
    public List<HistoryActivity> selectHistorySingle(String instanceId) {
        List<HistoricActivityInstance> list = historyService.createHistoricActivityInstanceQuery()
                .processInstanceId(instanceId)
                .activityType("userTask")//活动类型为userTasK
                .orderByHistoricActivityInstanceStartTime()
                .asc()//没有默认升序需要手动加上
                .list();
        if (list == null) {
            Collections.emptyList();
        }
        ArrayList<HistoryActivity> historyActivities = new ArrayList<>();

        for (HistoricActivityInstance h:list
             ) {
            HistoryActivity historyActivity = new HistoryActivity();
            BeanUtils.copyProperties(h, historyActivity);
            List<Comment> comments = taskService.getTaskComments(h.getTaskId(), "comment");//批注类型加上
            List<String> collect = comments.stream().map(comment -> comment.getFullMessage()).collect(Collectors.toList());
            if (!CollectionUtils.isEmpty(collect)) {
                historyActivity.setComment(collect.get(0));
            }
            historyActivity.setAssigneeName(h.getAssignee());
            historyActivities.add(historyActivity);
        }
        return historyActivities;
    }
}
